package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.UserLocation;
import com.itheima.service.mongo.UserLocationService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.net.CacheRequest;
import java.util.ArrayList;
import java.util.List;

@DubboService
public class UserLocationServiceImpl implements UserLocationService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveLocation(Double latitude, Double longitude, String addrStr, Long userId) {
        // 1.查询地理位置是否存在
        UserLocation userLocation = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)), UserLocation.class);
        // 2.判断
        if (userLocation == null) {
             // 新增
            userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
            userLocation.setAddress(addrStr);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            mongoTemplate.save(userLocation);
        }else{
            // 修改
            userLocation.setLocation(new GeoJsonPoint(latitude, longitude)); // 新坐标
            userLocation.setAddress(addrStr); // 新位置描述
            userLocation.setLastUpdated(userLocation.getUpdated());// 上次更新时间
            userLocation.setUpdated(System.currentTimeMillis());// 本次更新时间
            mongoTemplate.save(userLocation);
        }
    }


    // 搜附近
    @Override
    public List<Long> searchNearUser(Long userId, Long distance) {
        // 1.找圆心
        GeoJsonPoint location = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)), UserLocation.class).getLocation();

        // 2.指定半径（公里/千米）
        Distance dis = new Distance(distance/1000, Metrics.KILOMETERS);

        // 3.画圆
        Circle circle = new Circle(location, dis);

        // 4.条件搜索
        List<UserLocation> userLocationList = mongoTemplate.find(new Query(Criteria.where("location").withinSphere(circle)), UserLocation.class);

        // 5.遍历获取用户id
        List<Long> nearUserId = new ArrayList<>();

        for (UserLocation userLocation : userLocationList) {
            nearUserId.add(userLocation.getUserId());
        }
        return nearUserId;
    }
}
